import path from "path";
import { defineConfig, loadEnv, ProxyOptions } from "vite";
import { getServiceEnvConfig } from "./.env-config";
import { setupVitePlugins } from "./build";

/**
 * 设置网络代理
 * @param isOpenProxy - 是否开启代理
 * @param envConfig - env环境配置
 */
export function createViteProxy(
  isOpenProxy: boolean,
  envConfig: ServiceEnvConfigWithProxyPattern
) {
  if (!isOpenProxy) {
    return undefined;
  }

  const proxy: Record<string, string | ProxyOptions> = {
    [envConfig.proxyPattern]: {
      target: envConfig.url,
      changeOrigin: true,
      rewrite: (path: any) =>
        path.replace(new RegExp(`^${envConfig.proxyPattern}`), ""),
    },
  };

  return proxy;
}

export default defineConfig((configEnv: any) => {
  const rootPath = path.resolve(process.cwd());
  const viteEnv = loadEnv(
    configEnv.mode,
    process.cwd()
  ) as unknown as ImportMetaEnv;
  // 查看是否需要代理
  const isOpenProxy = viteEnv.VITE_HTTP_PROXY === "Y";
  const envConfig = getServiceEnvConfig(viteEnv);
  return {
    plugins: setupVitePlugins(viteEnv),
    server: {
      host: "0.0.0.0",
      port: 3200,
      open: true,
      proxy: createViteProxy(isOpenProxy, envConfig),
    },
    resolve: {
      alias: {
        "~": path.resolve(process.cwd()),
        "@": `${rootPath}/src`,
      },
    },
  };
});

// https://vitejs.dev/config/
// export default defineConfig({
//   plugins: [vue()],
// })
